<?php

namespace app\shop\controller\collect\api;

use app\common\model\collect\OrderExpressGoodsModel;
use app\common\model\collect\OrderExpressModel;
use app\common\model\jiyun\OrderInfoExpressModel;
use app\common\model\shop\OrderInfoModel;
use app\common\service\CollectService;
use app\common\model\shop\OrderModel;
use app\common\model\shop\PlatformModel;
use think\admin\Controller;
use think\admin\service\AdminService;
use think\facade\Log;

/**
 * 采集商品脚本
 *
 * @Description
 * @package app\shop\controller\collect\api
 * @author wangqinghui
 * @date 2024-10-21 10:31
 */
class Info extends Controller
{

    /**
     * 采集操作入口
     * @Description
     * @author wangqinghui
     * @date 2024-11-28 11:14
     * @return void
     */
    public function action()
    {
        $action = $this->request->post('act', '');
        switch ($action){
            case 'isLogin':// 校验登录
                $this->check_login();
                break;
            case 'goods_detail':// 商品详情
                $this->goods_detail();
                break;
            case 'goods_list':// 商品列表
                $this->goods_list();
                break;
            case 'collectOrder':// 采集订单
                $this->order_detail();
                break;
            case 'getOrderNo':// 获得erp订单
                $this->get_order_no();
                break;
            default:
                $this->error('无效的请求');
        }
    }

    /**
     * 商品详情
     *
     * @Description
     * @author wangqinghui
     * @date 2024-10-21 10:31
     * @return void
     */
    protected function goods_detail()
    {
        $post_data = $this->request->post(false);
        $html = $post_data['data'] ?? '';
        $goodsUrl = $post_data['goods_url'] ?? '';
        //Log::info('【详情采集】内容:'.$html);
        if(empty($html) || empty($goodsUrl)){
            $this->error('采集失败,暂未获取到数据');
        }

        // 采集数据分析过滤处理逻辑
        try {
            $collect_service = new CollectService();
            $collect_service->init($goodsUrl)->handel($html, $goodsUrl)->addOrUpdateCollectData();
        } catch (\Exception $e) {
            $this->error('采集失败,'.$e->getMessage());
        }
        $this->success('采集成功');
    }

    /**
     * 列表页采集
     *
     * @Description
     * @author wangqinghui
     * @date 2024-10-30 13:51
     * @return void
     */
    protected function goods_list()
    {
        // 设置 CORS 头
        header("Access-Control-Allow-Origin: *"); // 允许所有来源，也可以指定特定的来源
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); // 允许的 HTTP 方法
        header("Access-Control-Allow-Headers: Content-Type, Authorization"); // 允许的请求头

        $post_data_str = $this->request->post('data', '');
        if(empty($post_data_str)){
            $this->error('采集失败,暂未获取到数据');
        }
        $post_data = json_decode($post_data_str, 1);
        if(empty($post_data)){
            $this->error('采集失败,暂未获取到数据');
        }
        $count = $err_count = $suc_count = 0;
        // 实例化采集服务
        $collect_service = new CollectService();
        foreach ($post_data as $key => $value) {
            $count ++;
            $url = $value['url'] ?? '';
            $goodsUrl = $value['detail_url'] ?? '';
            $html = http_get($url, []);
            // 采集数据分析过滤处理逻辑
            try {
                $collect_service->init($goodsUrl)->handel($html, $goodsUrl)->addOrUpdateCollectData();
                $suc_count ++;
            } catch (\Exception $e) {
                Log::error('【列表采集】采集失败,url:'.$url.';error:'.$e->getMessage());
                $err_count ++;
            }
        }
        $this->success('采集成功,共采集'.$count.'条数据,成功'.$suc_count.'条,失败'.$err_count.'条');
    }

    /**
     * 校验用户是否登录
     * @Description
     * @author wangqinghui
     * @date 2024-11-28 13:38
     * @return void
     */
    protected function check_login()
    {
        // 校验是否登录
        $is_login = AdminService::isLogin();
        if(!$is_login){
            $this->error('请先登录');
        }
        $this->success('登录成功');
    }

    /**
     * 采集订单数据
     * @Description
     * @author wangqinghui
     * @date 2024-11-29 16:05
     * @return void
     */
    protected function order_detail()
    {
        $order_data = $this->request->post('data', []);
        if(empty($order_data)){
            $this->error('采集失败,暂未获取到订单数据');
        }
        $order_no_arr = array_column($order_data, 'orderId');
        if(empty($order_no_arr)){
            $this->error('采集失败,暂未获取到订单号');
        }
        $from = (int)$order_data[0]['platform'];
        // 校验订单是否存在
        $map = [
            ['order_no', 'in', $order_no_arr],
            ['from',    '=', $from]
        ];
        $field = 'id,from,order_no,express_no';
        $old_order_list = OrderExpressModel::mk()->field($field)->where($map)->select()->toArray();
        $old_order_data = [];
        if(!empty($old_order_list)){
            foreach ($old_order_list as $key => $value) {
                $old_order_data[$value['order_no']][$value['express_no']] = $value['id'];
            }
        }
        $order_no       = ''; // 商城的订单
        $other_order_no = []; //三方的订单
        $add_data = $add_goods_data = [];
        foreach ($order_data as $key => $info) {

            $order_no         = $info['order_no'];
            $other_order_no[] = $info['orderId'];
            $temp = [
                'from'          =>  $info['platform'],
                'shop_account_id'   =>  $this->account_id,
                'order_no'      =>  $info['orderId'],
                'order_time'    =>  $info['orderTime'],
                'order_detail_url'  =>  $info['url'],
            ];
            if(!empty($info['expressList'])){
                $is_exist_flag = false;
                foreach ($info['expressList'] as $e_key => $e_value) {
                    $temp['express_company']  = $e_value['express_company'];
                    $temp['express_no']     = $e_value['express_no'];
                    $temp['delivery_time']    = $e_value['delivery_time'];
                    if(!empty($old_order_data[$info['orderId']][$e_value['express_no']])){
                        $order_express_id = $old_order_data[$info['orderId']][$e_value['express_no']];
                        OrderExpressModel::mk()->where('id', $order_express_id)->update($temp);
                    }else{
                        if(!empty($old_order_data[$info['orderId']]) && empty($is_exist_flag)){
                            $order_express_id = !empty($old_order_data[$info['orderId']]['']) ? $old_order_data[$info['orderId']][''] : 0;
                            OrderExpressModel::mk()->where('id', $order_express_id)->update($temp);
                            $is_exist_flag = true;
                        }else{
                            $order_express_id = OrderExpressModel::mk()->insertGetId($temp);
                        }
                    }
                    if(!empty($e_value['sku_list'])){
                        $map = [
                            'order_express_id'  =>  $order_express_id
                        ];
                        OrderExpressGoodsModel::mk()->where($map)->delete();
                        foreach ($e_value['sku_list'] as $s_key => $s_value) {
                            $good_temp = [
                                'order_express_id'  =>  $order_express_id,
                                'name'    =>  $s_value['name'],
                                'num'     =>  $s_value['num'],
                                'spec_value'   =>  $s_value['spec_value'],
                                'image'     =>  $s_value['image'],
                            ];
                            $add_goods_data[] = $good_temp;
                        }
                    }
                }
            }else{
                if(!empty($old_order_data[$info['orderId']])){
                    $edit_id = !empty($old_order_data[$info['orderId']]['']) ? $old_order_data[$info['orderId']][''] : 0;
                    if(!empty($edit_id)){
                        OrderExpressModel::mk()->where('id', $edit_id)->update($temp);
                    }
                }else{
                    $add_data[] = $temp;
                }
            }
        }

        if(!empty($add_data)){
            $count = OrderExpressModel::mk()->insertAll($add_data);
            if($count <= 0){
                $this->error('采集失败,订单数据添加失败');
            }
        }
        if(!empty($add_goods_data)){
            $count = OrderExpressGoodsModel::mk()->insertAll($add_goods_data);
            if($count <= 0){
                $this->error('采集失败,订单商品数据添加失败');
            }
        }

        if ( $order_no ) {

            $order_obj = OrderModel::mk()->where('order_no', $order_no)->where('account_id', $this->adminUser['account_id'])->find();
            if(!empty($other_order_no)){
                $map = [];
                foreach ($other_order_no as $key => $value) {
                    // 查询单号是否已被占用
                    $map[] = [
                        ['other_order_no', 'find in set', $value]
                    ];
                }
                $exist_list = OrderModel::mk()->where('id', '<>', $order_obj->id)->where(function ($query) use($map){
                    $query->whereOr($map);
                })->column('other_order_no');
                if(!empty($exist_list)){
                    $exist_other_order_no_str = implode(',', $exist_list);
                    $err_arr = array_intersect($other_order_no, explode(',', $exist_other_order_no_str));
                    $this->error('采购单号已被占用:'.implode('|', $err_arr));
                }
            }

            $order_obj->other_order_no && $other_order_no  = array_merge($other_order_no, explode(',',$order_obj->other_order_no));

            $other_order_no = array_unique(array_filter($other_order_no));

            $order_obj->other_order_no = implode(',', $other_order_no);

            $order_obj->save();
        }

        $this->success('采集成功');
    }

    /**
     * 获得用户等单号
     *
     * @return void
     */
    public function get_order_no ()
    {

        $field = 'id,platform_id,shop_id,order_no';
        $list = OrderModel::mk()->field($field)->where('sync_status' , 1)->where('account_id', $this->adminUser['account_id'])->select()->toArray();
        if(!empty($list)){
            $platform_ids = array_column($list, 'platform_id');
            $platform_data = [];
            if(!empty($platform_ids)){
                $platform_data = PlatformModel::mk()->where('id', 'in', $platform_ids)->column('title', 'id');
            }
            foreach ($list as $key => $value) {
                $list[$key]['platform_name'] = !empty($platform_data[$value['platform_id']]) ? $platform_data[$value['platform_id']] : [];
            }
        }

        $this->success('成功', $list);
    }
}